/*
 * @Author: ykp 501436989@qq.com
 * @Date: 2025-05-03 16:09:09
 * @LastEditors: ykp 501436989@qq.com
 * @LastEditTime: 2025-05-18 16:03:25
 * @FilePath: \vue-ts\src\views\todolist\components\indexeddbOperations.ts
 * @Description: 这是默认设置,请设置`customMade`, 打开koroFileHeader查看配置 进行设置: https://github.com/OBKoro1/koro1FileHeader/wiki/%E9%85%8D%E7%BD%AE
 */
import type { ListType } from "@/type/todolist/card"; //引入ts类型定义
/**
 * @description: 新增单条详情数据
 * @param {ListType} item  
 * @return {*}
 */
export const addItem = function (item: ListType) {
  return new Promise((resolve, reject) => {
    const request = indexedDB.open("myDatabase", 1);
    // 数据库打开成功时触发
    request.onsuccess = function (event: any) {
      const db = event.target.result;
      // 开始一个事务
      const transaction = db.transaction(["urgencyList"], "readwrite");
      // 获取对象存储空间
      const objectStore = transaction.objectStore("urgencyList");
      // 添加数据，手动提供唯一的键值
      const data = item;
      const addRequest = objectStore.add(data);
      addRequest.onsuccess = function (event: any) {
        // 读取数据
        const getRequest = objectStore.get(item.id);
        getRequest.onsuccess = async function (event: any) {
          await db.close();
          resolve(true)

        };
        getRequest.onerror = function (event: any) {
          reject(new Error('添加数据时出错'));
          db.close();
        };
      };
      addRequest.onerror = function (event: any) {
        reject(new Error('添加数据时出错'));
        db.close();
      };
      // 事务完成时触发
      transaction.oncomplete = function () {
        db.close();
      };
    };
    // 数据库打开失败时触发
    request.onerror = function (event: any) {
      reject(new Error('打开数据库时出错'));
      console.error("打开数据库时出错:", event.target.error);
    };
  })
}
/**
 * @description: 更新单条详情数据
 * @param {ListType} item 
 * @return {*}
 */
export const putItem = function (item: ListType) {
  return new Promise((resolve, reject) => {
    // 打开数据库
    const request = indexedDB.open('myDatabase', 1);
    // 数据库打开成功时触发
    request.onsuccess = function (event: any) {
      const db = event.target.result;
      // 开始一个读写事务
      const transaction = db.transaction(['urgencyList'], 'readwrite');
      const objectStore = transaction.objectStore('urgencyList');
      // 要更新的数据
      const updatedData = item;
      // 使用 put() 方法更新数据
      const updateRequest = objectStore.put(updatedData);
      updateRequest.onsuccess = function (event: any) {
        console.log('数据更新成功');
        resolve(true)
      };
      updateRequest.onerror = function (event: any) {
        console.log('数据更新失败');
        reject(new Error('数据更新失败'));
        db.close();
      };
      // 事务完成时触发
      transaction.oncomplete = function (event: any) {
        db.close();
      };
      // 事务出错时触发
      transaction.onerror = function (event: any) {
        console.log('事务出错:', event.target.error);
        reject(new Error('事务出错'));
        db.close();
      };
    };
    // 数据库打开失败时触发
    request.onerror = function (event) {
      console.log('数据库打开失败');
      reject(new Error('数据库打开失败'));
    };
  })
}
/**
 * @description: 删除单条详情数据
 * @param {string} id 数据id
 * @return {*}
 */
export const deleteItem = function (id: string) {
  return new Promise((resolve, reject) => {
    // 打开数据库
    const request = indexedDB.open('myDatabase', 1);
    // 数据库打开成功时触发
    request.onsuccess = function (event: any) {
      const db = event.target.result;
      // 开始一个读写事务
      const transaction = db.transaction(['urgencyList'], 'readwrite');
      const objectStore = transaction.objectStore('urgencyList');
      // 要删除的数据的键
      const keyToDelete = id;
      // 使用 delete() 方法删除数据
      const deleteRequest = objectStore.delete(keyToDelete);
      deleteRequest.onsuccess = function (event: any) {
        console.log('数据删除成功');
        resolve(true)
        db.close();
      };
      deleteRequest.onerror = function (event: any) {
        console.log('数据删除失败');
        reject(new Error('数据删除失败'));
        db.close();
      };
      // 事务完成时触发
      transaction.oncomplete = function (event: any) {
        db.close();
      };
      // 事务出错时触发
      transaction.onerror = function (event: any) {
        reject(new Error('事务出错:', event.target.error));
        // console.log('事务出错:', event.target.error);
      };
    };
    // 数据库打开失败时触发
    request.onerror = function (event: any) {
      reject(new Error('数据库打开失败'));
      // console.log('数据库打开失败');
    };
  })
}
/**
 * @description: 查询数据
 * @param {string} queryType :查询类型
 * @param {any} queryDetails :查询详情
 * @param {string} queryType1 :查询类型 多条件
 * @param {any} queryDetails1 :查询详情
 * @return {*}
 */
export const querylist = function (queryType?: string, queryDetails?: any, queryType1?: string, queryDetails1?: any) {
  return new Promise((resolve, reject) => {
    // 打开数据库
    const request = indexedDB.open('myDatabase', 1);
    let arrs: ListType[] = []
    // 数据库打开成功时触发
    request.onsuccess = function (event: any) {
      const db = event.target.result;
      // 开始一个只读事务
      const transaction = db.transaction(['urgencyList'], 'readonly');
      const objectStore = transaction.objectStore('urgencyList');
      // 打开游标，遍历对象存储空间中的所有数据
      const cursorRequest = objectStore.openCursor();
      cursorRequest.onsuccess = function (event: any) {
        const cursor = event.target.result;
        if (cursor) {
          // 处理当前数据
          // console.log('遍历到的数据:', cursor.value[queryType]);
          // 移动到下一条记录
          if (queryType1 && cursor.value[queryType1] === queryDetails1 && queryType && cursor.value[queryType] === queryDetails) {
            arrs.push(structuredClone(cursor.value))
          } else if (!queryType1 && queryType && cursor.value[queryType] === queryDetails) {
            arrs.push(structuredClone(cursor.value))
          } else if (!queryType) {
            arrs.push(structuredClone(cursor.value))
          }
          cursor.continue();
        } else {
          resolve(structuredClone(arrs))
          db.close()
          // console.log(structuredClone(arrs))
          // console.log('数据遍历结束');
        }
      };
      cursorRequest.onerror = function (event: any) {
        // console.log('数据遍历失败');
        reject(new Error('数据库打开失败'));
        db.close()
      };
      // 事务完成时触发
      transaction.oncomplete = function (event: any) {
        db.close();
      };
      // 事务出错时触发
      transaction.onerror = function (event: any) {
        // console.log('事务出错:', event.target.error);
        reject(new Error('事务出错'));
      };
    };
    // 数据库打开失败时触发
    request.onerror = function (event: any) {
      // console.log('数据库打开失败');
      reject(new Error('数据库打开失败'));
    };
  })
}
/**
 * @description:查询单条详情 
 * @param {string} id  依靠id 查询详情
 * @return {*} 返回数据
 */
export const queryDetails = function (id: string) {
  return new Promise((resolve, reject) => {
    // 打开数据库
    const request = indexedDB.open('myDatabase', 1);
    let arrs: ListType[] = []
    // 数据库打开成功时触发
    request.onsuccess = function (event: any) {
      const db = event.target.result;
      // 开始一个只读事务
      const transaction = db.transaction(['urgencyList'], 'readonly');
      const objectStore = transaction.objectStore('urgencyList');
      const index = objectStore.index('id');
      const results: ListType[] = [];

      // 使用游标遍历所有匹配的记录
      const request = index.openCursor(IDBKeyRange.only(id));

      request.onsuccess = (event: any) => {
        const cursor = event.target.result;
        if (cursor) {
          results.push(cursor.value);
          cursor.continue();
        } else {
          resolve(results);
        }
      };

      // 事务完成时触发
      transaction.oncomplete = function (event: any) {
        db.close();
      };
      // 事务出错时触发
      transaction.onerror = function (event: any) {
        // console.log('事务出错:', event.target.error);
        reject(new Error('事务出错'));
      };
    };
    // 数据库打开失败时触发
    request.onerror = function (event: any) {
      // console.log('数据库打开失败');
      reject(new Error('数据库打开失败'));
    };
  })
}